﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MergeCodeTool
{
    class Program
    {
        static string srcProjectPath; // 原项目路径
        static string newProjectPath; // 新项目路径-合并后的文件输出

        static Configuration config;

        static void Main(string[] args)
        {
            Console.Title = "合并代码到一个文件中-工具";

            config = Configuration.Build();

            srcProjectPath = CmdReader.ReadLine("请输入存放代码的路径：", input => Directory.Exists(input));

            newProjectPath = CmdReader.ReadLine("请输入合并后代码文件保存位置：", input => Directory.Exists(input));
            
            Console.WriteLine("正在处理...");

            StreamWriter sw = null;
            try
            {
                //创建输出流，将得到文件名子目录名保存到txt中
                sw = new StreamWriter(new FileStream(newProjectPath+ "\\MergeCode.txt", FileMode.Append));
                getDirectory(sw, srcProjectPath, 2);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    Console.WriteLine("完成");
                }
            }

            Console.WriteLine($"完成！\r\n合并后的文件保存在：{newProjectPath}");
            Console.Write("请按任意键退出！");
            Console.ReadKey();
        }

        /// <summary>
        /// 获得指定路径下所有文件名
        /// </summary>
        /// <param name="sw">文件写入流</param>
        /// <param name="path">文件写入流</param>
        /// <param name="indent">输出时的缩进量</param>
        public static void getFileName(StreamWriter sw, string path, int indent)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (FileInfo f in root.GetFiles())
            {
                if (config.ContainExtensions.Contains(Path.GetExtension(f.FullName)))
                {
                    //包含的CS文件，才合并
                    //sw.WriteLine(f.FullName);
                    string str = File.ReadAllText(f.FullName);
                    sw.WriteLine(str);
                }
            }
        }

        /// <summary>
        /// 获得指定路径下所有子目录名
        /// </summary>
        /// <param name="sw">文件写入流</param>
        /// <param name="path">文件夹路径</param>
        /// <param name="indent">输出时的缩进量</param>
        public static void getDirectory(StreamWriter sw, string path, int indent)
        {
            var paths = path.Split('\\');
            var dirName = paths[paths.Length - 1];
            if (config.IgnoreFolders.Contains(dirName))
                return;
            getFileName(sw, path, indent);
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (DirectoryInfo d in root.GetDirectories())
            {
                getDirectory(sw, d.FullName, indent + 2);
            }
        }
    }
}
